package com.question.Exception;



import com.question.common.Result;
import com.question.enums.ResultEnums;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Result exceptionHandler(BaseException ex){
        logger.error(ex.getMessage());
        System.out.println(ex);
        return Result.error(ResultEnums.ERRORS.code, ex.getMessage());

    }
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        System.out.println("异常信息"+ex.getMessage());
        String message=ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split=message.split(" ");
            String username=split[2];
            String msg=username+"已存在";
            return Result.error(ResultEnums.ERRORS.code, msg);
        }else{
            return Result.error(ResultEnums.ERRORS.code, ex.getMessage());
        }

    }

}
